package bk;

public class PhoneBook {
	private static final int MAX_PERSON = 3;
	Person[] PhoneList = new Person[MAX_PERSON];
	private static int LastPerson = -1;
	
	public void insertNewPerson(String IpName, String IpPhoneNumber)
	{
		if(LastPerson == MAX_PERSON - 1)
		{
			System.out.println("PhoneBook is full!");
			return;
		}
		else{
			LastPerson++;
			if (PhoneList[LastPerson] == null)
			{
				PhoneList[LastPerson] = new Person();
			}
			PhoneList[LastPerson].setName(IpName);
			PhoneList[LastPerson].setPhoneNumber(IpPhoneNumber);
			this.sortByName();
			System.out.println("Insert " + IpName + " sucessfull!");
		}
	}
	
	public boolean setPhoneNumber(String IpName, String IpPhoneNumber)
	{
		for(int i = 0; i <= LastPerson; i++)
		{
			if(PhoneList[i].getName().equalsIgnoreCase(IpName) == true)
			{
				PhoneList[i].setPhoneNumber(IpPhoneNumber);
				return true;
			}
		}
		return false;
	}
	
	public void deletePerson(String IpName)
	{
		for(int i = 0; i <= LastPerson; i++)
		{
			if(PhoneList[i].getName().equalsIgnoreCase(IpName) == true)
			{
				PhoneList[i].setName(PhoneList[LastPerson].getName());
				PhoneList[i].setPhoneNumber(PhoneList[LastPerson].getPhoneNumber());
				PhoneList[LastPerson].setName(null);
				PhoneList[LastPerson].setPhoneNumber(null);
				LastPerson--;
			}
		}
		this.sortByName();
	}
	
	public void searchByName(String IpName)
	{
		for(int i = 0; i <= LastPerson; i++)
		{
			if(PhoneList[i].getName().equalsIgnoreCase(IpName) == true)
			{
				System.out.println("His/Her Phone Number: " + PhoneList[i].getPhoneNumber());
			}
		}
	}
	
	public void searchByPhoneNumber(String IpPhoneNumber)
	{
		for(int i = 0; i <= LastPerson; i++)
		{
			if(PhoneList[i].getPhoneNumber().equalsIgnoreCase(IpPhoneNumber) == true)
			{
				System.out.println("This phone number is belong to: " + PhoneList[i].getName());
				break;
			}
		}
	}
	
	public void sortByName() //Bubble sort
	{
		for (int i = 0; i <= LastPerson - 1; i++)
		{
			for (int j = i+1; j <= LastPerson; j++)
			{
				if(PhoneList[i].getName().compareToIgnoreCase(PhoneList[j].getName()) > 0)
				{
					swap(i,j);
				}
			}
		}
	}
	
	public void swap(int index1, int index2)
	{
		String temp = PhoneList[index1].getName();
		PhoneList[index1].setName(PhoneList[index2].getName());
		PhoneList[index2].setName(temp);
		temp = PhoneList[index1].getPhoneNumber();
		PhoneList[index1].setPhoneNumber(PhoneList[index2].getPhoneNumber());
		PhoneList[index2].setPhoneNumber(temp);
	}
	
	public String toString()
	{
		System.out.println("\nCurrent Phone List:");
		for (int i = 0; i <= LastPerson; i++ )
		{
			System.out.println("Person " + i + ": " + PhoneList[i].getName());
			System.out.println("Phone Number : "+ PhoneList[i].getPhoneNumber());
		}
		return "";
	}
}
